package net.jqsoft.mvc.controller;

import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.google.common.base.Throwables;

import net.jqsoft.common.domain.JsonResult;

@ControllerAdvice
public class ExceptionHandlerController {

	private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandlerController.class);

	@ResponseStatus
	@ResponseBody
	@ExceptionHandler(value = Exception.class)
	public JsonResult exception(HttpServletRequest request, Exception exception) {
		LOGGER.warn(exception.getMessage(), exception);
		String uri = request.getRequestURI();
		return JsonResult.build().respond(JsonResult.OPERATE_FAILURE)
				.add("error", Throwables.getRootCause(exception).getMessage())
				.add("status", Throwables.getRootCause(exception).getCause()).add("path", uri)
				.add("message", exception.getMessage());
	}
}